<template>
  <el-card class="padding">
    <el-form inline @submit.prevent>
      <el-form-item>
        <el-input placeholder="角色名称" v-model="searchRoleName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search" type="primary" @click="searchWithRoleName"
          >查询</el-button
        >
        <el-button @click="clearSearchRoleName">清空</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="addRole">添加</el-button>
    <el-button type="danger" :disabled="isDisable" @click="batchRemove"
      >批量删除</el-button
    >

    <el-table
      :data="roleList"
      border
      class="my-20"
      v-loading="isLoading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      ></el-table-column>
      <el-table-column
        type="index"
        label="序号"
        width="65"
        align="center"
      ></el-table-column>
      <el-table-column label="角色名称">
        <template #default="{ row }">
          <el-input
            type="text"
            v-if="row.isEdit"
            ref="editRoleRef"
            v-model="roleName"
            @blur="inputBlur(row)"
            @keyup.enter="inputBlur(row)"
            size="small"
          />
          <span v-else>{{ row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="250">
        <template #default="{ row }">
          <el-tooltip content="分配权限" placement="top" effect="light">
            <el-button
              :icon="InfoFilled"
              type="info"
              size="small"
              @click="toRoleAuth(row.id, row.roleName)"
            ></el-button
          ></el-tooltip>

          <el-tooltip content="修改角色" placement="top" effect="light">
            <el-button
              :icon="Edit"
              type="primary"
              size="small"
              @click="editRole(row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除角色" placement="top" effect="light">
            <div class="inline-block">
              <el-popconfirm
                :title="`确定删除<${row.roleName}>吗？`"
                @confirm="deleteRole(row.id)"
              >
                <template #reference>
                  <el-button
                    :icon="Delete"
                    type="danger"
                    size="small"
                  ></el-button
                ></template>
              </el-popconfirm>
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 20, 30, 40]"
      small
      :disabled="false"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>
</template>

<script lang="ts">
export default {
  name: 'ZRole',
}
</script>

<script lang="ts" setup>
import { Search, InfoFilled, Edit, Delete } from '@element-plus/icons-vue'
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getRoleListApi,
  addRoleApi,
  updataRoleApi,
  removeRole,
} from '@/api/role/roleApi'
import type { RoleType } from '@/api/role/model/roleType'

// 跳转页面
const router = useRouter()
const toRoleAuth = (id: string, roleName: string) => {
  router.push({ path: '/acl/role/auth', query: { id, roleName } })
}

const isLoading = ref(false)

// 删除角色的功能
const deleteRole = async (id: string) => {
  await removeRole(id)
  ElMessage.success('删除成功')
  getRoleList()
}

// 修改角色的功能
const roleName = ref('')
const editRoleRef = ref()
let lastRoleName: string
// 点击修改角色
const editRole = async (row: RoleType) => {
  row.isEdit = true
  roleName.value = row.roleName
  lastRoleName = roleName.value
  await nextTick()
  editRoleRef.value.focus()
}
// 输入框视区焦点
const inputBlur = async (row: RoleType) => {
  row.isEdit = false
  if (roleName.value == lastRoleName) return
  isLoading.value = true
  await updataRoleApi(roleName.value, row.id)
  getRoleList()
}

// 角色数据
const roleList = ref<RoleType[]>([])
const searchRoleName = ref('')
// 封装请求roleList数据的函数
const getRoleList = async () => {
  isLoading.value = true
  const res = await getRoleListApi(
    currentPage.value,
    pageSize.value,
    searchRoleName.value
  )
  total.value = res.total
  roleList.value = res.items.map((item) => {
    item.isEdit = false
    return item
  })
  isLoading.value = false
}

// 组件挂载请求数据
onMounted(getRoleList)

// 分页数据
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(5)
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize
  getRoleList()
}
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage
  getRoleList()
}

// 添加角色
const addRole = () => {
  ElMessageBox.prompt('请输入新名称', '添加角色', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  })
    .then(async ({ value }) => {
      if (!value.trim()) {
        ElMessage.warning('请输入角色名!')
        return
      }
      await addRoleApi(value)
      getRoleList()
      ElMessage({ type: 'success', message: '添加角色成功' })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消',
      })
    })
}

const isDisable = ref(true)
// 批量勾选的函数
const handleSelectionChange = (roleList: RoleType[]) => {
  const idList = roleList.map((role) => role.id)
  console.log(idList)
  //
}
// 批量删除按钮
const batchRemove = () => {
  //
}
// 按角色名搜索
const searchWithRoleName = () => {
  currentPage.value = 1
  getRoleList()
}
// 清空搜索条件
const clearSearchRoleName = () => {
  searchRoleName.value = ''
  getRoleList()
}
</script>

<style scoped>
.my-20 {
  margin: 20px 0;
}
.inline-block {
  display: inline-block;
  margin-left: 10px;
}
.padding {
  padding-right: 400px;
  position: relative;
}
</style>
